package mcu.market.util;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;



public class DateUtil{
	/**
	 * "example : yyyy/MM/dd"
	 * @param twDate
	 * @return
	 * @throws ParseException
	 */

	public Date convertADDateToTWDate(String adDate) throws ParseException {
		return conver_TW_and_AD(adDate,false);
		
	}
	/**
	 * "example : twDate=102/01/01(民國)"
	 * @param twDate
	 * @return
	 * @throws ParseException
	 */
	public Date convertTWDateToADDate(String twDate) throws ParseException {
		return conver_TW_and_AD(twDate,true);
		
    }
	/**
	 * 
	 * @param twDate
	 * @param type
	 * @return
	 * @throws ParseException 
	 */
	private Date conver_TW_and_AD(String date,boolean type) throws ParseException {
		if(date.equals(""))return null;
        String addate = "";
        int yy =0;
        try{
        	if(type){
        		yy = Integer.valueOf((date.substring(0, date.indexOf("/"))).trim()).intValue() + 1911;
        	}else{
        		yy = Integer.valueOf((date.substring(0, date.indexOf("/"))).trim()).intValue() - 1911;
        	}
        	String year = String.valueOf(yy);
	        String last_d = date.substring(date.indexOf("/"), date.length());
	        addate = year + last_d;
        }catch(StringIndexOutOfBoundsException e){
        	throw new ParseException(addate, 0);
        }
        return StringToDate(addate,"yyyy/MM/dd");
	}
	/**
	 * 轉換日期
	 * @param str 
	 * @param fomat 格式 如1922/8/30 yyyy/mm/dd
	 * @return Date
	 * @throws ParseException 
	 */
	public Date StringToDate(String str,String fomat) throws ParseException {
		Date date=null;
		SimpleDateFormat sdf = new SimpleDateFormat(fomat);	
		date = sdf.parse(str);
	    return date;
		
	}
	/**
	 * 轉換日期
	 * @param fomat 格式 如1922/8/30 yyyy/mm/dd
	 * @return Stirng
	 */
	public String DateToString(Date date,String fomat) {
		String str=null;
		SimpleDateFormat dateFormat = new SimpleDateFormat(fomat);
	    str=dateFormat.format(date);
	    return str;
		
	}
}
